package com.example.demo.service;

import com.example.demo.model.*;
import com.example.demo.repository.*;
import com.example.demo.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class ImportService {

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private UserService userService;

    @Autowired
    private CollegeRepository collegeRepository;

    @Autowired
    private MajorRepository majorRepository;

    @Autowired
    private ClassRepository classRepository;

    // 导入学生数据
    public String importStudents(MultipartFile file) throws Exception {
        List<ExcelUtils.StudentData> studentDataList = ExcelUtils.parseStudentExcel(file);
        int successCount = 0;
        int failCount = 0;

        for (ExcelUtils.StudentData studentData : studentDataList) {
            try {
                // 查找或创建学院
                College college = null;
                if (studentData.getCollegeName() != null && !studentData.getCollegeName().isEmpty()) {
                    Optional<College> collegeOpt = collegeRepository.findByName(studentData.getCollegeName());
                    if (collegeOpt.isPresent()) {
                        college = collegeOpt.get();
                    } else {
                        College newCollege = new College();
                        newCollege.setName(studentData.getCollegeName());
                        newCollege.setCode("COLLEGE_" + System.currentTimeMillis());
                        newCollege.setDescription("导入时自动创建的学院");
                        newCollege.setStatus(College.Status.active);
                        college = collegeRepository.save(newCollege);
                    }
                }

                // 查找或创建专业
                Major major = null;
                if (college != null && studentData.getMajorName() != null && !studentData.getMajorName().isEmpty()) {
                    Optional<Major> majorOpt = majorRepository.findByNameAndCollegeId(studentData.getMajorName(), college.getId());
                    if (majorOpt.isPresent()) {
                        major = majorOpt.get();
                    } else {
                        Major newMajor = new Major();
                        newMajor.setName(studentData.getMajorName());
                        newMajor.setCode("MAJOR_" + System.currentTimeMillis());
                        newMajor.setCollegeId(college.getId());
                        newMajor.setDescription("导入时自动创建的专业");
                        newMajor.setStatus(Major.Status.active);
                        major = majorRepository.save(newMajor);
                    }
                }

                // 查找或创建班级
                Classes clazz = null;
                if (studentData.getClassName() != null && !studentData.getClassName().isEmpty()) {
                    Optional<Classes> classOpt = classRepository.findByName(studentData.getClassName());
                    if (classOpt.isPresent()) {
                        clazz = classOpt.get();
                    } else {
                        Classes newClass = new Classes();
                        newClass.setName(studentData.getClassName());
                        newClass.setCode("CLASS_" + System.currentTimeMillis());
                        newClass.setStatus(Classes.Status.active);
                        newClass.setGraduationStatus(Classes.GraduationStatus.studying);
                        clazz = classRepository.save(newClass);
                    }
                }

                // 检查学号是否已存在
                Optional<Student> existingStudent = studentService.getStudentByStudentNo(studentData.getStudentNo());
                if (existingStudent.isPresent()) {
                    // 学号已存在，跳过
                    failCount++;
                    continue;
                }

                // 创建用户
                User user = new User();
                user.setUsername(studentData.getStudentNo());
                user.setRealName(studentData.getName());
                user.setRole(User.Role.student);
                user.setStatus(User.Status.active);
                user.setPassword("$2a$10$7JB720yubVSOfvK5j6s0oOjGHOOzn2oLs1yLowJO0aPjJ9zJ5jEAu"); // 默认密码123456的哈希值
                user.setCreatedAt(LocalDateTime.now());
                user.setUpdatedAt(LocalDateTime.now());
                user = userService.saveUser(user);

                // 创建学生
                Student student = new Student();
                student.setUserId(user.getId());
                student.setStudentNo(studentData.getStudentNo());
                if (college != null) {
                    student.setCollegeId(college.getId());
                }
                if (major != null) {
                    student.setMajorId(major.getId());
                }
                if (clazz != null) {
                    student.setClassId(clazz.getId());
                }
                student.setEnrollmentYear(studentData.getEnrollmentYear());
                studentService.saveStudent(student);

                successCount++;
            } catch (Exception e) {
                failCount++;
                // 记录错误日志
                e.printStackTrace();
            }
        }

        return String.format("导入完成！成功：%d条，失败：%d条", successCount, failCount);
    }

    // 导入教师数据
    public String importTeachers(MultipartFile file) throws Exception {
        List<ExcelUtils.TeacherData> teacherDataList = ExcelUtils.parseTeacherExcel(file);
        int successCount = 0;
        int failCount = 0;

        for (ExcelUtils.TeacherData teacherData : teacherDataList) {
            try {
                // 查找或创建学院
                College college = null;
                if (teacherData.getCollegeName() != null && !teacherData.getCollegeName().isEmpty()) {
                    Optional<College> collegeOpt = collegeRepository.findByName(teacherData.getCollegeName());
                    if (collegeOpt.isPresent()) {
                        college = collegeOpt.get();
                    } else {
                        College newCollege = new College();
                        newCollege.setName(teacherData.getCollegeName());
                        newCollege.setCode("COLLEGE_" + System.currentTimeMillis());
                        newCollege.setDescription("导入时自动创建的学院");
                        newCollege.setStatus(College.Status.active);
                        college = collegeRepository.save(newCollege);
                    }
                }

                // 检查工号是否已存在
                Optional<Teacher> existingTeacher = teacherService.getTeacherByTeacherNo(teacherData.getTeacherNo());
                if (existingTeacher.isPresent()) {
                    // 工号已存在，跳过
                    failCount++;
                    continue;
                }

                // 创建用户
                User user = new User();
                user.setUsername(teacherData.getTeacherNo());
                user.setRealName(teacherData.getName());
                user.setRole(User.Role.teacher);
                user.setStatus(User.Status.active);
                user.setPassword("$2a$10$7JB720yubVSOfvK5j6s0oOjGHOOzn2oLs1yLowJO0aPjJ9zJ5jEAu"); // 默认密码123456的哈希值
                user.setCreatedAt(LocalDateTime.now());
                user.setUpdatedAt(LocalDateTime.now());
                user = userService.saveUser(user);

                // 创建教师
                Teacher teacher = new Teacher();
                teacher.setUserId(user.getId());
                teacher.setTeacherNo(teacherData.getTeacherNo());
                if (college != null) {
                    teacher.setCollegeId(college.getId());
                }
                teacher.setTitle(teacherData.getTitle());
                teacher.setEmploymentDate(teacherData.getEmploymentDate());
                teacherService.saveTeacher(teacher);

                successCount++;
            } catch (Exception e) {
                failCount++;
                // 记录错误日志
                e.printStackTrace();
            }
        }

        return String.format("导入完成！成功：%d条，失败：%d条", successCount, failCount);
    }
}